package xdp

import (
	"fmt"

	"github.com/hashicorp/go-multierror"
	"github.com/vishvananda/netlink"
)

func lookupLink(intf string) (*netlink.Link, error) {
	link, err := netlink.LinkByName(intf)
	if err != nil {
		return nil, err
	}
	return &link, nil
}

// forcing xdpgeneric for veth because https://www.netdevconf.org/0x13/session.html?talk-veth-xdp
// tuntap also requires this probably for the same reasons
func xdpFlags(linkType string) int {
	if linkType == "veth" || linkType == "tuntap" {
		return 2
	}
	return 0 // native xdp (xdpdrv) by default
}

func (c *Hook) addXdpToLink(intf string) error {

	var errs error
	link, errs := lookupLink(intf)
	if errs != nil {
		return fmt.Errorf("interface is not present. Please run `ip a` to list available interfaces")
	}
	err := netlink.LinkSetXdpFdWithFlags(*link, c.mod.XdpIpFilter.FD(), xdpFlags((*link).Type()))
	if err != nil {
		errs = multierror.Append(errs, err)
	}

	return errs
}

func (c *Hook) delXdpFromLink(intf string) error {

	var errs error
	link, errs := lookupLink(intf)
	err := netlink.LinkSetXdpFdWithFlags(*link, -1, xdpFlags((*link).Type()))
	if err != nil {
		errs = multierror.Append(errs, err)
	}
	return errs
}
